package com.aica.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 登录请求的处理，解析出请求中json的username与password
 * @author by
 * @date 2021/6/8 19:30
 */
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //校验请求头中ContentType的值
        if (MediaType.APPLICATION_JSON_UTF8_VALUE.equals(request.getContentType())
                || MediaType.APPLICATION_JSON_VALUE.equals(request.getContentType())) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest ;
            //获取请求中的输入流
            try (InputStream is = request.getInputStream()) {
                Map<String,String> authenticationBean = mapper.readValue(is, Map.class);
                //解析其中的账号与密码
                String username = authenticationBean.get("username");
                String password = authenticationBean.get("password");
                //参数不能为空
                if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
                    log.info("登录失败，参数不能为空");
                    throw new UsernameNotFoundException("登录失败，参数不能为空");
                }
                authRequest = new UsernamePasswordAuthenticationToken(username, password);

            } catch (IOException e) {
                //e.printStackTrace();
                log.info(request.getRemoteAddr() + "登录请求输入流异常。。。");
                authRequest = new UsernamePasswordAuthenticationToken("", "");
            }

            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        //如果不是则使用原来的校验方式
        return super.attemptAuthentication(request, response);
    }

}
